import json
import os

from commons.DB import MySQLUtils
from openapi import house_api


def write_detail_to_mysql():
    """将文件写入 mysql
    """
    
    # 读取文件夹中的文件名
    file_names = os.listdir(house_api.result_folder)
    # 对文件名进行排序
    sorted_file_names = sorted(file_names)
    
    dbUtil = MySQLUtils.DBUtil()

    # 循环读取文件夹中的 JSON 文件
    for filename in sorted_file_names:
        if filename.endswith('.json'):
            try:
                file_path = os.path.join(house_api.result_folder, filename)

                # 读取文件中的 JSON 数据，指定编码方式为 'utf-8'
                with open(file_path, 'r', encoding='utf-8') as file:
                    json_data = json.load(file)

                # 房产信息
                house_id = json_data['house']['houseId']
                house = json_data['house']

                # 跟进信息
                followsStr = ''  # getFollowsStr()

                # 构建插入数据的 SQL 查询
                sql = "INSERT INTO house.house(house_id, `section`, block_no, unit_no, cell, price, unit_price, area, room, hall, toilet, floor, total_floor, decoration, follows_str) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"
                values = (
                    house_id,
                    house['section'],
                    house['blockNo'],
                    house['unitNo'],
                    house['cell'],
                    house['price'],
                    house['unitPrice'],
                    house['area'],
                    house['room'],
                    house['hall'],
                    house['toilet'],
                    house['floor'],
                    house['totalFloor'],
                    house['decoration'],
                    followsStr
                )

                dbUtil.saveAsValues(sql, values)

                print(f"写入{house_id}成功")
            except Exception as e:
                print("发生异常:", str(e))

    # 打印输出文件路径
    print(f'Saved data to Excel file: {len(sorted_file_names)}')


def main():
    """ 定时下载房源全量数据
    """

    # 下载列表 json
    house_api.write_houses_json()
    
    # 根据列表数据下载详情  json
    house_api.write_house_detail_json()
    
    # json 文件写入到 mysql
    write_detail_to_mysql()
    
    # 下载跟进记录
    
    # 将跟进记录中不符合条件的房源，置为失效


if __name__ == '__main__':
    main()
